<?php
class Utils_Crawler
{
	/**
	 * Used by HTMLPurifer (class HTMLPurifier_AttrTransform_ImgRequired)
	 * Crawl the image, return the data, or a tmp file??
	 */ 
	public function crawlImage($imgUrl)
	{
		// This is actually exactly the same:
		
        $client = new Zend_Http_Client();
        
        $client->setUri($imgUrl);
        $client->setMethod(Zend_Http_Client::GET);
    
        $client->setConfig(array(
        	'useragent' => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1",
            'maxredirects' => 0,
            'timeout'      => 30));
         $response = $client->request();
         return $response->getBody();
	}

	/**
     * See HTMLPurifer for references.
     * save the image to appropriate file depending on userId, articleId, moduleName 
	 * E.g: In an article describing a place, it contains an image 
	 *   http://example.com/abc.jpg
	 * 		this function will be called to save this abc.jpg to /public/ufiles/$userId/image/place/$articleId/abc.jpg
	 * 		also it should update the article_media table;
	 * @return : new image url to be used by HTML Purifier.
	 */
	public function saveImage($image, $filename)//$articleId,  $moduleName, $userId)
	{
		//http://vnexpress.net/Files/Subject/3B/A0/DB/0B/1.jpg
		$dir = dirname($filename);
		if ( file_exists($dir) || mkdir($dir, 0777  , true) )
		{
    		$fh = fopen($filename, "a+" );
        	fwrite( $fh, $image );
    		fclose( $fh );
    		return true;
		}
		else 
			die("can't create dir");
	}
	//TODO: create a table to save the crawled image information :)
	public function processImage($remoteImgUrl)
	{
		$image = $this->crawlImage($remoteImgUrl);
		$auth = Zend_Auth::getInstance();
		if ($auth->hasIdentity())
			$userId = $auth->getIdentity()->id;
				
		$dir = "/public/ustore/" . $userId . "/images/original/article/common/";
		//create dir
		if ( !file_exists(APP_PATH.$dir))
			mkdir($dir, 0777  , true);
		
		//generate random file name
		do 
		{	
			$fileName = $this->str_makerand(8, true, true, false) . '.jpg';
		}
		while(file_exists(APP_PATH . $dir . $fileName));

		$this->saveImage($image, APP_PATH . $dir . $fileName);
		return $dir.$fileName;
	}
    
	// Make a random string which has length of $length
    function str_makerand ($length, $useupper=false,$usenumbers=false, $usespecial=false)
    {
        $charset = "abcdefghijklmnopqrstuvwxyz";
        if ($useupper)   $charset .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        if ($usenumbers) $charset .= "0123456789";
        if ($usespecial) $charset .= "~@#$%^*()_+-={}|][";   // Note: using all special characters this reads: "~!@#$%^&*()_+`-={}|\\]?[\":;'><,./";
        $key='';
        for ($i=0; $i<$length; $i++) $key .= $charset[(mt_rand(0,(strlen($charset)-1)))];
        return $key;
    }

	
}
?>
